package com.water.springmvc4.advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;


/*
 * @ControllerAdvice声明一个控制器建议，@ControllerAdvice组合了@Component注解，
 * 所以会自动注册为spring的bean
 */
@ControllerAdvice
public class ExceptionHandlerAdvice {
	
	/*
	 * @ExceptionHandler在此出定义全局处理，通过@ExceptionHandler的value属性过滤拦截的条件，
	 * 在此处我们可以看出我们拦截所有的Exception
	 */
	@ExceptionHandler(value = Exception.class)//2
	public ModelAndView exception(Exception exception, WebRequest request) {
		ModelAndView modelAndView = new ModelAndView("error");// error页面
		modelAndView.addObject("errorMessage", exception.getMessage());
		return modelAndView;
	}
	
	/*
	 * 此处使用@ModelAttribute注解将键值对添加到全局，
	 * 所有注解@RequestMapping的方法可获取此键值对
	 */
	@ModelAttribute //3
	public void addAttributes(Model model) {
		model.addAttribute("msg", "额外信息"); //3
	}
	
	/*
	 * 通过@InitBinder注解定制WebDataBinder
	 */
	@InitBinder //4
	public void initBinder(WebDataBinder webDataBinder) {
		webDataBinder.setDisallowedFields("id"); //5
	}

}
